<template>
  <el-form
    class="user-add-form"
    :model="form"
    :rules="rules"
    ref="form"
    @keyup.enter.native="onSubmit"
    v-loading="loading"
  >
    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item :label="$t('user.username')" prop="username">
          <el-input
            v-model="form.username"
            :placeholder="$t('user.username')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item class="email" prop="email" :label="$t('user.email')">
          <el-input
            v-model="form.email"
            :placeholder="$t('user.email')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.firstName')" prop="firstName">
          <el-input
            v-model="form.firstName"
            :placeholder="$t('user.firstName')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.lastName')" prop="lastName">
          <el-input
            v-model="form.lastName"
            :placeholder="$t('user.lastName')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.displayName')" prop="realName">
          <el-input
            v-model="form.realName"
            :placeholder="$t('user.displayName')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12" v-if="$hasPermission('sys:user:password')">
        <el-form-item label="Password" prop="password">
          <el-input
            v-model="form.password"
            disabled
            placeholder="Password"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.mobile')" prop="mobile">
          <el-input
            v-model="form.mobile"
            :placeholder="$t('user.mobile')"
          ></el-input>
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item :label="$t('user.businessPhones')" prop="businessPhones">
          <el-input
            v-model="form.businessPhones"
            :placeholder="$t('user.businessPhones')"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-divider content-position="left">JOB INFORMATION</el-divider>
      </el-col>
      <el-col :span="12">
        <el-form-item :label="$t('user.managerName')">
          <el-select
            v-model="form.managerId"
            style="width: 100%"
            filterable
            clearable
            default-first-option
            :placeholder="$t('user.managerName')"
          >
            <el-option
              v-for="item in managers"
              :key="item.id"
              :label="`${item.username} (${item.email})`"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="$hasPermission('sys:user:assignrole')">
        <el-form-item :label="$t('user.deptName')">
          <RenDeptTree
            v-model="form.deptId"
            :placeholder="$t('dept.title')"
            :dept-name.sync="form.deptName"
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="User Type" prop="regSource">
          <el-select
            v-model="form.regSource"
            style="width: 100%"
            placeholder="Select"
            :disabled="!$hasPermission('sys:user:assignrole')"
          >
            <el-option
              v-for="item in userTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-divider content-position="left">ACCOUNT INFORMATION</el-divider>
      </el-col>
      <el-col :span="24">
        <el-form-item prop="roleIds" :label="$t('user.roleIdList')">
          <el-select
            v-model="form.roleIds"
            multiple
            collapse-tags
            :disabled="!$hasPermission('sys:user:assignrole')"
            style="width: 100%"
            :placeholder="$t('user.roleIdList')"
          >
            <el-option
              v-for="item in roleOptions"
              :key="item.roleId"
              :label="item.name"
              :value="item.roleId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <ZCardSwitch
            label="Status"
            :active-value="1"
            :inactive-value="0"
            :disabled="!$hasPermission('sys:user:assignrole')"
            v-model="form.status"
            desc="After a user's account is suspended, that user will not be able to log in."
          />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item>
          <ZCardSwitch
            label="Message"
            v-model="form.teamsMessageSwitch"
            desc="After closing the message, the user's teams will no longer receive messages from MSPbots.ai."
          />
        </el-form-item>
      </el-col>
      <!-- <el-col :span="12">
        <el-form-item :label="$t('user.homeChannel')"> </el-form-item>
      </el-col> -->
      <el-col :span="12" v-if="$hasPermission('sys:report:homepage')">
        <el-form-item :label="$t('custom.component.viewComponent.homepage')">
          <el-select
            v-model="form.homePage"
            style="width: 100%"
            filterable
            clearable
            :placeholder="$t('custom.component.viewComponent.homepage')"
          >
            <el-option
              v-for="item in dashboards"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-divider content-position="left">
          THIRD-PARTY PLATFORM MAPPING
        </el-divider>
      </el-col>
      <el-col :span="12" v-if="settings['CW']">
        <el-form-item prop="cwUserMapping" :label="$t('user.cwUserMapping')">
          <el-select
            v-model="form.cwUid"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.cwUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.cwUserList"
              :key="item.cwUid"
              :label="item.email"
              :value="item.cwUid"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['TEAMS']">
        <el-form-item
          prop="teamsUserMapping"
          :label="$t('user.teamsUserMapping')"
        >
          <el-select
            v-model="form.teamsUserId"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.teamsUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.teamsUserList"
              :key="item.teamsUserId"
              :label="item.teamsMail"
              :value="item.teamsUserId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['TSHEET']">
        <el-form-item
          prop="sheetsUserMaapping"
          :label="$t('user.sheetsUserMaapping')"
        >
          <el-select
            v-model="form.sheetUserId"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.sheetsUserMaapping')"
          >
            <el-option
              v-for="item in mappingUsers.sheetsUserList"
              :key="item.sheetUserId"
              :label="item.email"
              :value="item.sheetUserId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['TD']">
        <el-form-item
          prop="timeDoctorUserMapping"
          :label="$t('user.timeDoctorUserMapping')"
        >
          <el-select
            v-model="form.timedoctorUser"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.timeDoctorUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.timedoctorUserList"
              :key="item.userId"
              :label="item.email"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['AUTOTASK']">
        <el-form-item
          prop="autotaskUserMapping"
          :label="$t('user.autotaskUserMapping')"
        >
          <el-select
            v-model="form.autotaskUser"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.autotaskUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.autotaskUserList"
              :key="item.userId"
              :label="item.email"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['SYNCROMSP']">
        <el-form-item
          prop="syncroUserMapping"
          :label="$t('user.syncroUserMapping')"
        >
          <el-select
            v-model="form.syncroUser"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.syncroUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.syncroUserList"
              :key="item.otherId"
              :label="item.email"
              :value="item.otherId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" v-if="settings['SYNCROMSP']">
        <el-form-item
          prop="kaseyabmsUserMapping"
          :label="$t('user.kaseyabmsUserMapping')"
        >
          <el-select
            v-model="form.kaseyabmsUser"
            style="width: 100%"
            filterable
            default-first-option
            :placeholder="$t('user.kaseyabmsUserMapping')"
          >
            <el-option
              v-for="item in mappingUsers.kaseyaBmsUserList"
              :key="item.otherId"
              :label="item.email"
              :value="item.otherId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <div class="flex justify-end items-center">
          <el-button size="small">{{ $t('cancel') }} </el-button>
          <el-button type="primary" size="small">
            {{ $t('confirm') }}
          </el-button>
        </div>
      </el-col>
    </el-row>
  </el-form>
</template>

<script>
import {
  fetchMappingUser,
  fetchRole,
  fetchAssignRole,
  fetchOldReportList
} from '@/api/new'
import ZCardSwitch from '@/components/storybook/z-card-switch'
import { intersectionBy } from 'lodash'
import { USER_TYPE_OPTIONS } from '@/components/storybook/b-user-actions/index.schema'

export default {
  name: 'UserAddForm',
  components: {
    ZCardSwitch,
  },
  props: {
    settings: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    const validatePassword = (rule, value, callback) => {
      if (!this.form.id && !/\S/.test(value)) {
        return callback(new Error(this.$t('validate.required')))
      }
      callback()
    }
    const validateConfirmPassword = (rule, value, callback) => {
      if (!this.form.id && !/\S/.test(value)) {
        return callback(new Error(this.$t('validate.required')))
      }
      if (this.form.password !== value) {
        return callback(new Error(this.$t('user.validate.confirmPassword')))
      }
      callback()
    }
    return {
      rules: {
        username: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        deptName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        regSource: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'change'
          }
        ],
        firstName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        lastName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        realName: [
          {
            required: true,
            message: this.$t('validate.required'),
            trigger: 'blur'
          }
        ]
      },
      form: {
        password: '0*HzMe@1972Z',
        confirmPassword: '0*HzMe@1972Z',
        regSource: '1',
        roleIds: [],
        gender: 0,
        status: 1,
        teamsMessageSwitch: true
      },
      loading: false,
      managers: [],
      mappingUsers: {
        autotaskUserList: [],
        cwUserList: [],
        kaseyaBmsUserList: [],
        sheetsUserList: [],
        syncroUserList: [],
        teamsUserList: [],
        timedoctorUserList: []
      },
      dashboards: [],
      roleOptions: [],
      roles: [],
      assignRoles: [],
      userTypeOptions: Object.freeze(USER_TYPE_OPTIONS)
    }
  },
  created () {
    this.init()
  },
  methods: {
    onChangeStatus (val) {
      if (!val) {
        if (
          !this.form.isGuestUser &&
          (this.form.cwUserName || this.form.autoTaskUserName)
        ) {
          this.$emit('event:change-status')
        }
      }
    },
    async init () {
      try {
        this.loading = true
        const [mappingUsers, dashboards, roles, assignRoles] =
          await Promise.all([
            this.getMappingUser(),
            this.getDashboards(),
            this.getRoles(),
            this.getAssingRoles()
          ])
        this.assignRoles = assignRoles
        this.roles = roles
        const assigns = this.assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')

        this.mappingUsers = {
          ...this.$options.data().mappingUsers,
          ...mappingUsers
        }
        this.dashboards = dashboards
      } catch (error) {
      } finally {
        this.loading = false
      }
    },
    onSubmit () {},
    async getMappingUser () {
      try {
        const params = {}
        const { data: response } = await fetchMappingUser(params)
        if (response.code !== 0) {
          throw response.msg
        }
        return response.data || {}
      } catch (error) {
        console.log(error)
        return {}
      }
    },
    async getDashboards () {
      try {
        const params = {
          queryType: 'REFRESHCACHE',
          layoutType: 'report_layout',
          showAllIntegration: false,
          resourceType:0
        }
        const { data: response } = await fetchOldReportList(params)
        if (response.code !== 0) {
          throw response.msg
        }
        return response.data || []
      } catch (error) {
        console.log(error)
        return []
      }
    },
    async getRoles () {
      try {
        const params = {
          tenantCode: this.$store.state.user.tenantCode
        }
        const { data: response } = await fetchRole(params)
        if (response.code !== 0) {
          throw response.msg
        }
        return response.data || []
      } catch (error) {
        console.log(error)
        return []
      }
    },
    async getAssingRoles () {
      try {
        const roleIds = (this.$store.state.user.roleList || []).map(
          ({ id }) => id
        )
        const params = {
          roleId: roleIds
        }
        const { data: response } = await fetchAssignRole(params)
        if (response.code !== 0) {
          throw response.msg
        }
        return response.data || []
      } catch (error) {
        console.log(error)
        return []
      }
    }
  }
}
</script>
